package com.huya.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class WechatDecryptUtil {
    // 解密用户信息（头像、昵称等）
    public static JSONObject decryptUserInfo(String encryptedData, String iv, String sessionKey) {
        try {
            byte[] keyBytes = Base64.getDecoder().decode(sessionKey);
            byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData);
            byte[] ivBytes = Base64.getDecoder().decode(iv);

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] decrypted = cipher.doFinal(encryptedBytes);

            String result = new String(decrypted, StandardCharsets.UTF_8);
            return JSON.parseObject(result);
        } catch (Exception e) {
            throw new RuntimeException("用户信息解密失败", e);
        }
    }

    // 解密手机号（单独接口处理）
    public static String decryptPhoneNumber(String encryptedData, String iv, String sessionKey) {
        JSONObject json = decryptUserInfo(encryptedData, iv, sessionKey);
        return json.getString("purePhoneNumber");
    }
}
